//
//  RWAdvertViewController.m
//  baisibudejie
//
//  Created by renwei on 16/9/18.
//  Copyright © 2016年 renwei. All rights reserved.
//

#import "RWAdvertViewController.h"
#import "RWTabBarController.h"

#import "RWADItem.h"

#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import <UIImageView+WebCache.h>

/*
 1.广告业务逻辑
 2.占位视图思想:有个控件不确定尺寸,但是层次结构已经确定,就可以使用占位视图思想
 3.屏幕适配.通过屏幕高度判断
 */

#define code2 @"phcqnauGuHYkFMRquANhmgN_IauBThfqmgKsUARhIWdGULPxnz3vndtkQW08nau_I1Y1P1Rhmhwz5Hb8nBuL5HDknWRhTA_qmvqVQhGGUhI_py4MQhF1TvChmgKY5H6hmyPW5RFRHzuET1dGULnhuAN85HchUy7s5HDhIywGujY3P1n3mWb1PvDLnvF-Pyf4mHR4nyRvmWPBmhwBPjcLPyfsPHT3uWm4FMPLpHYkFh7sTA-b5yRzPj6sPvRdFhPdTWYsFMKzuykEmyfqnauGuAu95Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiu9mLfqHbD_H70hTv6qnHn1PauVmynqnjclnj0lnj0lnj0lnj0lnj0hThYqniuVujYkFhkC5HRvnB3dFh7spyfqnW0srj64nBu9TjYsFMub5HDhTZFEujdzTLK_mgPCFMP85Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiuBnHfdnjD4rjnvPWYkFh7sTZu-TWY1QW68nBuWUHYdnHchIAYqPHDzFhqsmyPGIZbqniuYThuYTjd1uAVxnz3vnzu9IjYzFh6qP1RsFMws5y-fpAq8uHT_nBuYmycqnau1IjYkPjRsnHb3n1mvnHDkQWD4niuVmybqniu1uy3qwD-HQDFKHakHHNn_HR7fQ7uDQ7PcHzkHiR3_RYqNQD7jfzkPiRn_wdKHQDP5HikPfRb_fNc_NbwPQDdRHzkDiNchTvwW5HnvPj0zQWndnHRvnBsdPWb4ri3kPW0kPHmhmLnqPH6LP1ndm1-WPyDvnHKBrAw9nju9PHIhmH9WmH6zrjRhTv7_5iu85HDhTvd15HDhTLTqP1RsFh4ETjYYPW0sPzuVuyYqn1mYnjc8nWbvrjTdQjRvrHb4QWDvnjDdPBuk5yRzPj6sPvRdgvPsTBu_my4bTvP9TARqnam"


@interface RWAdvertViewController ()

@property (nonatomic, strong) UIImageView   *launchImageView;
@property (nonatomic, strong) UIView        *adContainView;
@property (nonatomic, strong) UIImageView   *adImageView;
@property (nonatomic, strong) UIButton      *jumpButton;

@property (nonatomic, strong) RWADItem      *item;

// 定时器
@property (nonatomic ,weak) NSTimer         *timer;
@end

@implementation RWAdvertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 加载数据
    [self loadAdData];
    // 设置主界面
    [self createMainView];
    // 设置启动图片
    [self setupLaunchImage];
    // 创建定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
}

#pragma mark - 加载广告数据
- (void)loadAdData {

    // 1.创建请求会话管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    // 2.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"code2"] = code2;
    
    // 3.发送请求
    [mgr GET:@"http://mobads.baidu.com/cpro/ui/mads.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求数据 -> 解析数据（写成plist文件） -> 设计模型 －> 字典转模型 -> 展示数据
//        [responseObject writeToFile:@"/Users/admin/Desktop/未命名文件夹/ad.plist" atomically:YES];
//        NSLog(@"%@",responseObject);
        
        // 取出字典
        NSDictionary *adDict = [responseObject[@"ad"] firstObject];
        
        // 字典转模型
        _item = [RWADItem mj_objectWithKeyValues:adDict];
        
        RWLog(@"--------%@", _item);
        // 创建UIImageView展示图片 =>
        CGFloat h = RWScreenW / _item.w * _item.h;
        self.adImageView.frame = CGRectMake(0, 0, RWScreenW, h);
        // 加载广告页
        [self.adImageView sd_setImageWithURL:[NSURL URLWithString:_item.w_picurl]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark - 设置界面
//**设置主界面*/
- (void)createMainView {
    
    self.launchImageView = [[UIImageView alloc] init];
    
    self.adContainView = [[UIView alloc] init];
    _adContainView.backgroundColor = [UIColor clearColor];
    
    self.jumpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_jumpButton setBackgroundColor:[UIColor colorWithRed:0/255 green:0/255 blue:0/255 alpha:0.5]];
    [_jumpButton setTitle:[NSString stringWithFormat:@"跳转 (3)"] forState:UIControlStateNormal];
    [_jumpButton addTarget:self action:@selector(clickJumpButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_launchImageView];
    [self.view addSubview:_adContainView];
    [self.view addSubview:_jumpButton];
    
    [_launchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [_adContainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_launchImageView);
    }];
    
    [_jumpButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_adContainView).offset(20);
        make.right.equalTo(_adContainView).offset(-20);
    }];
}

//**设置启动图片*/
-(void)setupLaunchImage {
    
    // 6p:LaunchImage-800-Portrait-736h@3x.png
    // 6:LaunchImage-800-667h@2x.png
    // 5:LaunchImage-568h@2x.png
    // 4s:LaunchImage@2x.png
    if (iphone6P) { // 6p
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"];
    } else if (iphone6) { // 6
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-667h"];
    } else if (iphone5) { // 5
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-568h"];
        
    } else if (iphone4) { // 4
        
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-700"];
    }
}

#pragma mark - 监听方法
- (void)tapAdImageView {
    
    // 跳转到界面 => safari
    NSURL *url = [NSURL URLWithString:_item.ori_curl];
    UIApplication *app = [UIApplication sharedApplication];
    if ([app canOpenURL:url]) {
        [app openURL:url];
    }
}

- (void)timeChange {

    // 倒计时
    static int i = 3;
    
    if (i == 0) {
        
        // 跳转到主界面
        [self clickJumpButton];
    }
    
    i --;
    
    // 设置跳转文字
    [_jumpButton setTitle:[NSString stringWithFormat:@"跳转 (%d)",i] forState:UIControlStateNormal];
}

- (void)clickJumpButton {
    // 销毁广告界面,进入主框架界面
    
    RWTabBarController *tabBarVc = [[RWTabBarController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVc;
    
    // 干掉定时器
    [_timer invalidate];

}

#pragma mark  - 懒加载
- (UIImageView *)adImageView {
    
    if (_adImageView == nil) {
        UIImageView *imageView = [[UIImageView alloc] init];
        
        [self.adContainView addSubview:imageView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAdImageView)];
        [imageView addGestureRecognizer:tap];
        
        imageView.userInteractionEnabled = YES;
        
        
        _adImageView = imageView;
    }
    
    return _adImageView;
}

@end
